<template>
	<div class="home">
		<div class="top">
			<van-icon name="arrow-left" size="20px" @click="goback()" />
			<div>录入信息</div>
		</div>

		<!-- img -->
		<div class="idcard">
			<div>
				<img url="url1" :src="url1" alt="">
				<input type="file" id="upload" url="url1" accept="image/*" @change="upload">
			</div>
			<div>
				<img url="url2" :src="url2" alt="">
				<input type="file" id="upload" url="url2" accept="image/*" @change="upload">
			</div>
		</div>
		<van-divider :style="{ color: '#black', borderColor: 'black', padding: '0 6px' }">
			照片要求
		</van-divider>

		<div class="images">
			<div>
				<img src="../assets/img/v2_pztgnb.png" alt="">
				<p>照片清晰
					<img src="../assets/img/ok.png" alt="">
				</p>

			</div>
			<div>
				<img src="../assets/img/v2_pztgso.png" alt="">
				<p>边框丢失
					<img src="../assets/img/error.png" alt="">
				</p>

			</div>
			<div>
				<img src="../assets/img/v2_pztguh.png" alt="">
				<p>曝光太强
					<img src="../assets/img/error.png" alt="">
				</p>

			</div>
			<div>
				<img src="../assets/img/v2_pzth1t.jpg" alt="">
				<p>拍摄模糊
					<img src="../assets/img/error.png" alt="">
				</p>

			</div>
		</div>
		<p class="getImg" @click="getImg">上传提取</p>
		<van-divider :style="{ color: '#black', borderColor: 'black', padding: '0 6px' }">
			以下信息上传身份证后自动提取
		</van-divider>

		<van-cell-group>
			<van-field label-width="50px" :value="name" label="姓名:" readonly />
			<van-field label-width="50px" :value="gender" label="性别:" readonly />
			<van-field label-width="50px" :value="birthday" label="生日:" readonly />
			<van-field label-width="50px" :value="race" label="民族:" readonly />
			<van-field :value="id_card_number" label-width="80px" label="身份证号:" readonly class="bottom" />
			<van-field :value="address" label-width="80px" label="住址:" readonly class="bottom" />
		</van-cell-group>

		<p class="getImg" @click="goerweima">确定无误,下一步</p>

	</div>
</template>

<script>
	import { Divider } from 'vant';
	import { mapState, mapMutations } from 'vuex'
	import Exif from 'exif-js'
	import { Toast } from "vant"
	import { Field } from 'vant'
	export default {
		data() {
			return {
				url1: require('../assets/img/v2_pztgk1.jpg'),
				url2: require('../assets/img/v2_pztgk2.jpg'),
				file1: null,
				file2: null,
				name: "",
				gender: "",
				birthday: "",
				race: "",
				address: "",
				id_card_number: "",
				downloadurl: "https://wallet.95516.com/s/wl/webV3/activity/yhtzB/html/snsIndex.html?r=c31d969e469fb33f458a32dccc72096a&code=yhtzc2c",

			}
		},
		computed: mapState(['token', 'userInfo', 'userid']),
		methods: {
			// 如果methods里面还有其他函数，就要在辅助函数名称的前面加上扩展运算符
			...mapMutations(['changeidCard']),
			goerweima() {
				let that = this
				const { name, gender, birthday, race, address, id_card_number, url } = this

				if (!name || !gender || !birthday || !race || !address || !id_card_number || !url) {
					Toast("请上传身份证照片")
					return
				}
				this.$axios.get('/idcard/addidcard', {
					params: {
						user_id: this.userid,
						name,
						gender,
						birthday,
						race,
						address,
						id_card_number,
						url
					}
				}).then((res) => {
					const { data, status } = res
					console.log(res)
					if (status == 200 && data.code == 200) {
						localStorage.setItem('idCard', this.id_card_number)
						this.changeidCard(this.id_card_number)
						// that.$router.push({
						// 			name: "enter1"
						// 		})
						// Toast(res.data.message)
						
						Toast({
							message: res.data.message,
							onClose: () => {
								that.$router.push({
									name: "property"
								})
								plus.runtime.openURL(this.downloadurl, function (res) {

								})

							}
						})
					} else {
						Toast(data.message)
					}
				})
			},
			goback() {
				this.$router.back()
			},
			getImg() {
				// console.log(this.file1, this.file2)
				if (!this.file1 || !this.file2) {
					Toast("请选择照片")
					return
				}
				const formdata = new FormData()
				let file = this.file1
				// console.log(file)
				formdata.append('file', file);
				this.$axios.post("/kaungshi/idcard", formdata, {
					headers: {
						'Content-Type': 'multipart/form-data',
						'token': this.token,
					}
				}).then((res) => {
					const { data, status } = res
					console.log(res)
					if (status == 200 && data.code == 400) {
						Toast(data.message)
						return
					} else if (status == 200 && data.code == 200) {
						let data1 = data.data
						this.address = data1.address
						this.birthday = data1.birthday
						this.gender = data1.gender
						this.id_card_number = data1.id_card_number
						this.name = data1.name
						this.race = data1.race
						this.url = data1.url
					}
				})

			},
			upload(e) {
				// files为传进来的图片文件
				console.log(e)
				let url = e.target.attributes.url.nodeValue
				console.log(url)
				let files = e.target.files || e.dataTransfer.files;
				// console.log(files)
				if (!files.length) return;
				this.picValue = files[0];
				// console.log("picValue", this.picValue)
				var timestamp = Date.parse(new Date())
				this.filename = timestamp + this.picValue.name
				this.imgPreview(this.picValue, url);
			},
			imgPreview(file, url) {
				let self = this;
				let Orientation;
				//去获取拍照时的信息，解决拍出来的照片旋转问题
				Exif.getData(file, function () {
					Orientation = Exif.getTag(this, 'Orientation');
				});
				// 看支持不支持FileReader
				if (!file || !window.FileReader) return;

				if (/^image/.test(file.type)) {
					// 创建一个reader
					let reader = new FileReader();
					// 将图片2将转成 base64 格式
					reader.readAsDataURL(file);
					// 读取成功后的回调
					reader.onloadend = function () {
						let result = this.result;
						let img = new Image();
						self.base64 = result
						img.src = result;
						// console.log( "img",img.src)
						//判断图片是否小于100K,是就直接上传，反之压缩图片
						if (this.result.length <= (100 * 1024)) {
							// console.log("没压缩了")
							if (url == "url1") {
								self.url1 = this.result;
								self.file1 = self.dataURLtoFile(self.headerImage, self.filename)
							} else {
								self.url2 = this.result;
								self.file2 = self.dataURLtoFile(self.headerImage, self.filename)
							}

							// console.log("base64", self.headerImage)


							self.postImg();
						} else {
							// console.log("压缩了")
							img.onload = function () {
								let data = self.compress(img, Orientation);

								if (url == "url1") {
									self.url1 = data;
									self.file1 = self.dataURLtoFile(data, self.filename)
								} else {
									self.url2 = data;
									self.file2 = self.dataURLtoFile(data, self.filename)
								}
								// console.log("base64", self.headerImage)


								// console.log(data)
								self.postImg();
							}
						}
					}
				}
			},
			postImg() {
				//这里写接口
				// console.log("000")
			},
			rotateImg(img, direction, canvas) {
				//最小与最大旋转方向，图片旋转4次后回到原方向    
				const min_step = 0;
				const max_step = 3;
				if (img == null) return;
				//img的高度和宽度不能在img元素隐藏后获取，否则会出错    
				let height = img.height;
				let width = img.width;
				let step = 2;
				if (step == null) {
					step = min_step;
				}
				if (direction == 'right') {
					step++;
					//旋转到原位置，即超过最大值    
					step > max_step && (step = min_step);
				} else {
					step--;
					step < min_step && (step = max_step);
				}
				//旋转角度以弧度值为参数    
				let degree = step * 90 * Math.PI / 180;
				let ctx = canvas.getContext('2d');
				switch (step) {
					case 0:
						canvas.width = width;
						canvas.height = height;
						ctx.drawImage(img, 0, 0);
						break;
					case 1:
						canvas.width = height;
						canvas.height = width;
						ctx.rotate(degree);
						ctx.drawImage(img, 0, -height);
						break;
					case 2:
						canvas.width = width;
						canvas.height = height;
						ctx.rotate(degree);
						ctx.drawImage(img, -width, -height);
						break;
					case 3:
						canvas.width = height;
						canvas.height = width;
						ctx.rotate(degree);
						ctx.drawImage(img, -width, 0);
						break;
				}
			},
			compress(img, Orientation) {
				let canvas = document.createElement("canvas");
				let ctx = canvas.getContext('2d');
				//瓦片canvas
				let tCanvas = document.createElement("canvas");
				let tctx = tCanvas.getContext("2d");
				let initSize = img.src.length;
				let width = img.width;
				let height = img.height;
				//如果图片大于四百万像素，计算压缩比并将大小压至400万以下
				let ratio;
				if ((ratio = width * height / 4000000) > 1) {
					// console.log("大于400万像素")
					ratio = Math.sqrt(ratio);
					width /= ratio;
					height /= ratio;
				} else {
					ratio = 1;
				}
				canvas.width = width;
				canvas.height = height;
				//        铺底色
				ctx.fillStyle = "#fff";
				ctx.fillRect(0, 0, canvas.width, canvas.height);
				//如果图片像素大于100万则使用瓦片绘制
				let count;
				if ((count = width * height / 1000000) > 1) {
					// console.log("超过100W像素");
					count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
					//            计算每块瓦片的宽和高
					let nw = ~~(width / count);
					let nh = ~~(height / count);
					tCanvas.width = nw;
					tCanvas.height = nh;
					for (let i = 0; i < count; i++) {
						for (let j = 0; j < count; j++) {
							tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
							ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
						}
					}
				} else {
					ctx.drawImage(img, 0, 0, width, height);
				}
				//修复ios上传图片的时候 被旋转的问题
				if (Orientation != "" && Orientation != 1) {
					switch (Orientation) {
						case 6://需要顺时针（向左）90度旋转
							this.rotateImg(img, 'left', canvas);
							break;
						case 8://需要逆时针（向右）90度旋转
							this.rotateImg(img, 'right', canvas);
							break;
						case 3://需要180度旋转
							this.rotateImg(img, 'right', canvas);//转两次
							this.rotateImg(img, 'right', canvas);
							break;
					}
				}
				//进行最小压缩
				let ndata = canvas.toDataURL('image/jpeg', 0.1);
				// console.log('压缩前：' + initSize);
				// console.log('压缩后：' + ndata.length);
				// console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
				tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
				// console.log(ndata)

				return ndata;

			},
			dataURLtoFile(dataurl, filename) {//将base64转换为文件
				var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], filename, { type: mime });
			},
			getCommunityList() {
				let that = this
				this.$axios.get('/comm/getuserReviewStatus', {
					params: {
						user_id: this.userid
					}
				}).then((res) => {
					//console.log(res);
					let { message, data, status } = res;
					console.log(res)
					if (status == 200) {
						if (data.idcard_state == 2) {
							if (data.comm_state == 1) {
								this.$router.push("enter1")
								Toast("身份信息已录入,请绑定小区")
							}
							if (data.comm_state == 4) {
								this.$router.push("enter1")
								Toast("信息审核失败,请重新绑定小区")
							}
						} 
					}
				})
			},
		},
		// this.token相当于this.$store.state.token
		created() {
			this.getCommunityList()
		},
	}
</script>

<style lang="scss" scoped>
	.home {
		padding-top: 40px;
	}

	.top {
		position: fixed;
		top: 0;
		height: 40px;
		line-height: 40px;
		/* position: relative; */
		font-size: 16px;
		border-bottom: 1px solid #999;
		width: 100%;
		background-color: #4b77e4;
		z-index: 9999;
		color: white;
	}

	.top div {
		text-align: center;

	}

	.van-icon-arrow-left {
		position: absolute;
		top: 10px;
	}

	.idcard {
		display: flex;
		justify-content: space-around;
		margin-top: .2rem;

		div {
			width: 45%;
			position: relative;
			height: 2.5rem;

			img {
				width: 100%;
				height: auto;
				max-height: 100%;
				border-radius: 8px;
			}
		}

	}

	.van-divider {
		margin: 5px auto !important;
	}

	.images {
		display: flex;
		justify-content: space-between;
		text-align: center;

		div {
			width: 24%;

			img {
				width: 100%;
				height: 50px;
				max-width: 90px;
			}

			p {
				position: relative;

				img {
					position: absolute;
					right: 5px;
					width: 20px;
					height: auto;
				}
			}
		}
	}

	.getImg {
		width: 30%;
		background-color: #4b77e4;
		color: white;
		text-align: center;
		margin: 8px auto;
		height: 30px;
		line-height: 30px;
		border-radius: 4px;
	}

	#upload {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 1;
		opacity: 0;
	}

	.van-cell-group {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		margin-bottom: .4rem;

		.van-cell {
			width: 50%;

			.van-field__label {
				width: 30px !important;
			}
		}

	}

	.bottom {
		width: 100% !important;
	}
</style>